class ParkingLotList extends React.Component {
    constructor(props) {
        super(props);
        this.page = 1;
        this.layerIndex;
        this.isPerms = hasPerms('car:parkinglot:create');
        this.state = {
            list: '',
            laneList: '',
            parkId: 0,
            parkInfo: '',
            editIndex: {}
        }
    }

    componentDidMount() {
    }

    assignedChange(data) {
        this.queryList(1);
    }

    fixedQueueSwitch(checked, parkId) {
        postJson('/car/parkingLot/createFixedQueue.x', {
            parkId: parkId,
            isCreate: checked
        })
    }

    queueLaneSwitch(checked, carLaneId) {
        postJson('/car/carLane/createQueue.x', {
            carLaneId: carLaneId,
            isCreate: checked
        })
    }

    addParkingLot(parkId) {
        this.refs.addParkingLot.editParkingLot(parkId);
        this.refs.modal_add_parking_lot.show();
    }

    queryList(page) {
        //保证通过之后还是在当前页
        if (page > 1 && this.state.list.length === 1) {
            page = page - 1;
        }
        this.updateList(page, 10);
    }

    updateList(page, pageSize) {
        let params = {};
        params.page = page;
        params.pageSize = pageSize;
        params.commCode = this.refs.buildingSelectList.commCode;
        postJson("/car/parkingLot/queryParkingLotList.x", params, (data) => {
            this.page = params.page;
            this.setState({
                list: data.list
            });
        });
    }

    tbody() {
        if (this.state.list) {
            return this.state.list.map((array) => {
                return (<tr>
                    <td>{array.park_id}</td>
                    <td>{array.park_name}</td>
                    <td>{array.creation_time}</td>
                    <td>{array.description}</td>
                    <td>车位数：{array.month_card_num}&nbsp;&nbsp;&nbsp;剩余：{array.month_card_remain_num}</td>
                    <td>车位数：{array.guest_num}&nbsp;&nbsp;&nbsp;剩余：{array.guest_remain_num}</td>
                    <SecurityCheck perms="car:parkinglot:create">
                        <td>
                            <Checkbox
                                checked={array.fixed_queue === 1}
                                title="下行队列"
                                onClick={(data) => this.fixedQueueSwitch(data, array.park_id)}
                                lay-skin="primary"/>
                        </td>
                    </SecurityCheck>
                    <td>
                        <Button size="xs" onClick={() => this.monthlyRate(array)}>月卡费率</Button>
                        <Button size="xs" btnType="normal"
                                onClick={() => this.carLaneModal(array.park_id)}>车道管理</Button>
                        <Button size="xs" btnType="primary"
                                onClick={() => this.showImage(array.park_id)}>预支付二维码</Button>
                        <SecurityCheck perms="car:parkinglot:create">
                            <Button size="xs" btnType="primary"
                                    onClick={() => this.addParkingLot(array.park_id)}>编辑</Button>
                            <Button size="xs" btnType="danger"
                                    onClick={() => this.deleteParkingLot(array.park_id)}>删除</Button>
                        </SecurityCheck>
                    </td>
                </tr>)
            })
        }
    }

    carLaneTbody() {
        if (this.state.laneList) {
            return this.state.laneList.map((array) => {
                return (<tr>
                    <td>{array.laneName}</td>
                    <td>{array.laneCode}</td>
                    <td>{array.creationTime}</td>
                    <SecurityCheck perms="car:parkinglot:create">
                        <td>
                            <Checkbox
                                checked={array.msgQueue === 1}
                                onClick={(data) => this.queueLaneSwitch(data, array.id)}
                                lay-skin="primary"/>
                        </td>
                    </SecurityCheck>
                    <td>
                        <Button size="xs" btnType="primary"
                                onClick={() => this.showImage(array.parkId, array.laneCode)}>车道支付二维码</Button>
                    </td>
                </tr>)
            })
        }
    }

    showImage(parkId, laneCode) {
        let param = 'parkId=' + parkId;
        if (laneCode) {
            param += '&laneCode=' + laneCode
        }
        if (parkId) {
            layer.photos({
                photos: {
                    "title": "图片",
                    "data": [
                        {
                            "src": '/car/parkingLot/qrcode.x?' + param
                        }
                    ]
                }, anim: 5
            });
        } else {
            layer.msg("此记录无照片!");
        }
    }

    addSuccess() {
        this.queryList(this.page);
        this.refs.modal_add_parking_lot.close();
    }

    assigned(parkId, parkName) {
        let index = layer.confirm('确定要将（' + parkName + '）停车场分配到【' + this.refs.buildingSelectList.commCode + '】' + this.refs.buildingSelectList.commText + ' 小区？', {
            btn: ['确定', '取消']
        }, () => {
            postJson("/car/parkingLot/assignedParkingLot.x", $.param({
                'parkId': parkId,
                'commCode': this.refs.buildingSelectList.commCode
            }), () => {
                this.queryList(this.page);
                layer.close(index);
            });
        });
    }

    deleteParkingLot(id) {
        let index = layer.confirm('确定要删除？', {
            btn: ['确定', '取消']
        }, () => {
            postJson("/car/parkingLot/deleteParkingLot.x", $.param({
                'parkId': id
            }), () => {
                this.queryList(this.page);
                layer.close(index);
            });
        });
    }

    selectCommCallback(commCode) {
        this.queryList(1);
    }

    carLaneModal(parkId) {
        postJson('/car/carLane/queryCarLane.x', {parkId: parkId}, (data) => {
            this.setState({
                laneList: data.data
            }, () => {
                this.refs.modal_car_lane.show();
            });
        })

    }

    monthlyRate(parkInfo) {
        this.setState({
            parkId: parkInfo.park_id,
            parkInfo: parkInfo
        });
        postJson('/car/discount/queryDiscountList.x', {
            parkId: parkInfo.park_id
        }, (data) => {
            console.log("data", data);
            let list = data.data;
            for (let i in list) {
                this.refs['input_' + list[i].discountType + '_' + list[i].startMonth].value = list[i].discount;
            }
            this.refs['inputMonthly'].value = this.state.parkInfo.monthly_rate;
            this.refs.modal_monthly_rate.show();
        })
    }

    editMonthly(isEdit, monthly) {
        if (isEdit) {
            this.state.editIndex[monthly] = monthly;
            this.setState({})
        } else {
            console.log("monthly", this.state.parkInfo);
            postJson('/car/parkingLot/saveMonthlyRate.x', {
                parkId: this.state.parkInfo.park_id,
                monthlyRate: this.refs['inputMonthly'].value
            }, (data) => {
                this.state.editIndex[monthly] = null;
                this.updateList(1, 10);
            })
        }
    }

    monthlyEndCallback() {
        for (let i = 1; i < 13; i++) {
            let index = 'input_DISCOUNT_DIS_' + i;
            this.refs[index].value = '';
            this.state.editIndex[index] = null;
            index = 'input_DISCOUNT_GIVE_' + i;
            this.refs[index].value = '';
            this.state.editIndex[index] = null;
        }
        this.refs['inputMonthly'].value = '';
        this.state.editIndex['inputMonthly'] = null;
    }

    editClick(isEdit, type, monthly) {
        let index = 'input_' + type + '_' + monthly;
        if (isEdit) {
            this.state.editIndex[index] = index;
            this.setState({})
        } else {
            const reFloat = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/;
            const value = this.refs[index].value;
            if (!value || (reFloat.test(value) && value > 0 && ((type === 'DISCOUNT_DIS' && value < 1)) || ( type === 'DISCOUNT_GIVE'))) {
                postJson('/car/discount/saveDiscount.x', {
                    parkId: this.state.parkId,
                    startMonth: monthly,
                    discountType: type,
                    discount: value
                }, () => {
                    this.state.editIndex[index] = null;
                    this.setState({})
                })
            } else {
                this.refs[index].value = '';
                //提示层
                layer.msg('输入错误！请输入正确的优惠信息！！！');
            }
        }
    }

    preView(type) {
        let view = [];
        let inputView = [];
        for (let i = 1; i < 13; i++) {
            let index = 'input_' + type + '_' + i;
            inputView.push(<div>
                <Label>≥{i}个月</Label>
                {this.state.editIndex[index] ?
                    <ButtonInput size="sm" ref={index} frameStyle={{width: '50px'}}
                                 onClick={() => this.editClick(false, type, i)}>确定</ButtonInput>
                    :
                    <ButtonInput readonly="readonly" size="sm" ref={index} frameStyle={{width: '50px'}}
                                 onClick={() => this.editClick(true, type, i)}>编辑</ButtonInput>
                }
            </div>);
            if (i % 3 === 0 && i % 5 !== 0) {
                view.push(<Item>{
                    inputView
                }</Item>);
                inputView = [];
            }
        }
        return view;
    }

    render() {
        return <Frame header="停车场信息管理"
                      headerBtns={
                          [
                              <SecurityCheck perms="car:parkinglot:create">
                                  <HeaderBtn onClick={() => this.addParkingLot()}>添加停车场</HeaderBtn>
                              </SecurityCheck>
                          ]}>
            <Form type="pane">
                <Item>
                    <LayuiCommSelect
                        formLabelName="小区选择"
                        mask={['building', 'unit', 'floor', 'room']}
                        ref="buildingSelectList"
                        onChangeComm={(comm) => this.selectCommCallback(comm)}/>
                </Item>
                <Table ref="table" count={this.page}
                       pageOnClick={(page, pageSize) => this.updateList(page, pageSize)}>
                    <colgroup>
                        <col width="150"/>
                        <col/>
                        <col/>
                        <col/>
                        <col/>
                        <col/>
                        <SecurityCheck perms="car:parkinglot:create">
                            <col/>
                        </SecurityCheck>
                        <col width={this.isPerms ? 260 : 210}/>
                    </colgroup>
                    <thead>
                    <tr>
                        <th>停车场编号</th>
                        <th>停车场名称</th>
                        <th>创建时间</th>
                        <th>描述</th>
                        <th>月卡车位</th>
                        <th>访客（临停）车位数</th>
                        <SecurityCheck perms="car:parkinglot:create">
                            <th>消息队列</th>
                        </SecurityCheck>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    {this.tbody()}
                    </tbody>
                </Table>
                <Modal title="车道详情" ref="modal_car_lane" disableOverFlow={true}>
                    <Table ref="laneTable">
                        <colgroup>
                            <col/>
                            <col/>
                            <col/>
                            <SecurityCheck perms="car:parkinglot:create">
                                <col width="105"/>
                            </SecurityCheck>
                            <col width="100"/>
                        </colgroup>
                        <thead>
                        <tr>
                            <th>车道名称</th>
                            <th>车道编号</th>
                            <th>创建时间</th>
                            <SecurityCheck perms="car:parkinglot:create">
                                <th>消息队列</th>
                            </SecurityCheck>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {this.carLaneTbody()}
                        </tbody>
                    </Table>
                </Modal>

                <Modal title="月卡费率"
                       ref="modal_monthly_rate"
                       area={['auto']}
                       endCallback={() => this.monthlyEndCallback()}>
                    <Form type="pane" size="sm">
                        <Item>
                            <Label>月卡费率</Label>
                            {this.state.editIndex['inputMonthly'] ?
                                <ButtonInput size="sm"
                                             ref="inputMonthly"
                                             onClick={() => this.editMonthly(false, 'inputMonthly')}>确定</ButtonInput>
                                :
                                <ButtonInput readonly="readonly"
                                             size="sm"
                                             ref="inputMonthly"
                                             onClick={() => this.editMonthly(true, 'inputMonthly')}>编辑</ButtonInput>
                            }
                        </Item>
                        <Tab type="brief" titles={["打折优惠", "赠送优惠"]}>
                            <TabItem show={true}>
                                <Item>
                                    <div style={{color: '#4F94CD'}}>
                                        注：打折优惠是一次充值大于等于多少个月打折，如：一次充值3个月打8.5折，就在（≥3个月）输入0.85
                                    </div>
                                </Item>
                                {this.preView("DISCOUNT_DIS")}
                            </TabItem>
                            <TabItem>
                                <Item>
                                    <div style={{color: '#4F94CD'}}>
                                        注：赠送优惠是一次充值大于等于多少个月赠送月数，如：一次充值3个月送半个月，就在（≥3个月）输入0.5
                                    </div>
                                </Item>
                                {this.preView("DISCOUNT_GIVE")}
                            </TabItem>
                        </Tab>
                    </Form>
                </Modal>

                <SecurityCheck perms="car:parkinglot:create">
                    <Modal title="添加停车场" ref="modal_add_parking_lot">
                        <ParkingLot ref="addParkingLot" addSuccess={() => this.addSuccess()}/>
                    </Modal>
                </SecurityCheck>
            </Form>
        </Frame>
    }
}

ReactDOM.render(<ParkingLotList/>, document.getElementById('example'));
